<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue基础渲染</title>
</head>
<body>
  <div id="app">
    <p>{{ msg }}</p>
    <p>{{ name }}</p>
    <p>{{ obj.keyword }}</p>
  </div>
  <script>
    const regMustache = /\{\{\s*(\S+)\s*\}\}/
    class Vue {
      constructor ($options) {
        this._data = $options.data
        this.compile($options.el, this)
      }
      compile(el, vm) {
        vm._el = document.querySelector(el)
        const fragment =  document.createDocumentFragment()
        let childNode
        while(childNode = vm._el.firstChild) {
          fragment.appendChild(childNode)
        }
        //进行模板编译
        this.render(fragment, vm._data)
        vm._el.appendChild(fragment)
      }
      render (template, data) {
        const regMustache = /\{\{\s*(\S+)\s*\}\}/
        const childNodes = template.childNodes
        // console.log('childNodes', childNodes)
        for (let i = 0; i < childNodes.length; i++) {
          // 获取节点类型
          const type = childNodes[i].nodeType
          if (type == 3) { // 是文本节点
            // console.log('childNodes[i]', childNodes[i]);
            let nodeValue = childNodes[i].nodeValue // 获取文本节点内容
            // 替换模板内容
            // nodeValue = nodeValue.replace( regMustache, function (node, value) {
            //   let val = data[value]
            //   return val
            // })
            // childNodes[i].nodeValue = nodeValue
            const execResult = regMustache.exec(nodeValue)
            if (execResult) {
              const value = execResult[1].split('.').reduce((newObj, k) => newObj[k], data )
              childNodes[i].nodeValue = nodeValue.replace(regMustache,value)
            }
          } else if (type == 1) { // 是元素节点
            this.render(childNodes[i], data)
          }
        }
      }
    }
    new Vue({
      el: '#app',
      data: {
        msg: '你好啊',
        name: 'Alan',
        obj: {
          keyword: '测试'
        }
      }
    })
  </script>
</body>
</html>